﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using StockFinder.Model;

namespace StockFinder.NorgatePremiumData
{
    /// <summary>
    /// Gets list of stocks for PremiumData output
    /// </summary>
    public class NorgatePremiumDataStockFilePathsExtractor
    {
        const string DIRECTORY_SEED = @"C:\Trading Data\Formatted Output\";
        const string DELISTED = "Delisted";

        /// <summary>
        /// Gets list of stock price history filenames
        /// </summary>
        /// <returns></returns>
        public List<string> GetStockPriceHistoryFilenames()
        {
            //1 get files of stocks
            var stockFilePaths = new List<string>();

            foreach (var item in Directory.EnumerateDirectories(DIRECTORY_SEED))
            {
                if (!item.Contains(DELISTED))
                {
                    stockFilePaths.AddRange(Directory.EnumerateFiles(item));
                }                
            }            

            return stockFilePaths;
        }

        public string GetSymbolNameFromFileName(string filename)
        {
            var fileInfo = new FileInfo(filename);
            return fileInfo.Name.Replace(fileInfo.Extension, string.Empty).Trim();
        }

        public string GetExchangeNameFromFileName(string filename)
        {
            return filename.Split(new char[] { '\\' })[filename.Split(new char[] { '\\' }).Count() - 2];
        }

        public List<string> GetStockPriceHistoryFilenamesIncludingDelisted()
        {
            //1 get files of stocks
            var stockFilePaths = new List<string>();

            Directory.EnumerateDirectories(DIRECTORY_SEED).ToList().ForEach(d => stockFilePaths.AddRange(Directory.EnumerateFiles(d)));

            return stockFilePaths;
        }

        public List<string> GetStockPriceHistoryFilenamesIncludingDelisted(string directorySeed)
        {
            //1 get files of stocks
            var stockFilePaths = new List<string>();

            Directory.EnumerateDirectories(directorySeed).ToList().ForEach(d => stockFilePaths.AddRange(Directory.EnumerateFiles(d)));

            return stockFilePaths;
        }

        /// <summary>
        /// Gets list of stock price history filenames for specific exchange/directory
        /// </summary>
        /// <returns></returns>
        public List<string> GetStockPriceHistoryFilenamesForSpecificDirectoryName(string directoryName)
        {
            //1 get files of stocks
            var stockFilePaths = new List<string>();

            var directories = Directory.EnumerateDirectories(DIRECTORY_SEED).ToList();

            var matches = directories.Where(d => d.EndsWith(directoryName)).ToList();

            matches.ForEach(d => stockFilePaths.AddRange(Directory.EnumerateFiles(d)));

            return stockFilePaths;
        }

        /// <summary>
        /// Gets stock price history from specified filename
        /// </summary>
        /// <param name="filename"></param>
        /// <returns></returns>
        public List<DailyPrice> GetStockPriceHistoryFromFilename(string filename)
        {
            var historicPrices = new List<DailyPrice>();

            using (var sr = new StreamReader(filename))
            {
                string fileContents = sr.ReadToEnd();

                var lines = fileContents.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);                

                string line;

                for (int j = 0; j < lines.Count(); j++)
                {
                    //ignore the first line
                    if (j <= 0) continue;

                    line = lines[j];

                    if (string.IsNullOrEmpty(line)) continue;

                    var cells = line.Split(new string[] { "," }, StringSplitOptions.None);

                    historicPrices.Add(new DailyPrice()
                                           {
                                               PriceDate = DateTime.ParseExact(cells[0], "yyyyMMdd", null),
                                               Open = Convert.ToDecimal(cells[1]),
                                               High = Convert.ToDecimal(cells[2]),
                                               Low = Convert.ToDecimal(cells[3]),
                                               Close = Convert.ToDecimal(cells[4]),
                                               AdjustedClose = Convert.ToDecimal(cells[4]),
                                               Volume = Convert.ToDecimal(cells[5])
                                           });
                }
            }

            return historicPrices;
        }
    }
}
